import {Urls} from "./Urls";
import {Cookies} from "../common/Cookies";

export class Http {
    static post<T>(urlKey: string, body: any, param?: any): Promise<T> {
        let paramStr = this.handleUrl(urlKey, param);
        return fetch(paramStr, {
            body: JSON.stringify(body),
            method: 'post',
            headers: {'content-type': 'application/json'}
        }).then(res => res.json())
            .then(data => {
                return Http.handleResult(data)
            }).catch(e => {
                throw e;
            })
    }

    private static handleTokenParam(paramStr: string): string {
        let token = Cookies.getCookie(Cookies.TOKEN_KEY);
        if (token && token.length > 0) {
            paramStr += '&' + Cookies.TOKEN_KEY + '=' + token;
        }
        return paramStr;
    }

    static handleResult(data: any): any {
        if (data.hasOwnProperty("access_token")) {
            return data;
        } else {
            if (data.hasOwnProperty('success') && data.success) {
                return data.data;
            } else {
                throw Error(data.error);
            }
        }

    }

    static get<T>(urlKey: string, param?: any): Promise<T> {
        let url = this.handleUrl(urlKey, param);
        return fetch(url, {method: 'get'}).then(res => res.json())
            .then(data => {
                return Http.handleResult(data);
            }).catch(e => {
                throw e;
            })
    }

    private static handleUrl(urlKey: string, param: any) {
        let paramStr = Urls.getUrl(urlKey).url + '?_=' + new Date().getTime();
        paramStr = this.handleTokenParam(paramStr);
        if (param) {
            for (let paramKey in param) {
                if (param.hasOwnProperty(paramKey)) {
                    paramStr += '&' + paramKey + '=' + param[paramKey];
                }
            }
        }
        return paramStr;
    }
}